package com.goldwind.accompany.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;

import com.goldwind.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class OssService {

    private final OssConfig ossConfig;

    @Autowired
    public OssService(OssConfig ossConfig) {
        this.ossConfig = ossConfig;
    }

    public Map<String, String> generateUploadPolicy(String dir) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(
                ossConfig.getEndpoint(),
                ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret()
        );

        try {
            long expireEndTime = System.currentTimeMillis() + ossConfig.getExpireTime();
            Date expiration = new Date(expireEndTime);

            // 创建上传策略
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000); // 1GB
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            // 生成策略
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            // 构建返回结果 - 修复host格式
            Map<String, String> respMap = new LinkedHashMap<>();
            respMap.put("accessid", ossConfig.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);

            // 修复host格式 - 确保包含https://
            String host = "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint();
            respMap.put("host", host);

            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            respMap.put("callback", ossConfig.getCallbackUrl());

            return respMap;
        } catch (Exception e) {
            throw new RuntimeException("生成OSS上传策略失败", e);
        } finally {
            ossClient.shutdown();
        }
    }
}